
#include "lookaside.h"


namespace	memory
{
	lookaside::lookaside()
	{
		slists_ = NULL;
		count_ = 0;
	}

	lookaside::~lookaside()
	{
		destroy();
	}

	bool	lookaside::create( size_t count, unsigned short max )
	{
		assert( slists_ == NULL );
		if( slists_ != NULL )
		{
			return false;
		}

		if( count > 0 )
		{
			slists_ = new common::slist[count];
			if( slists_ == NULL )
			{
				return false;
			}

			for( size_t i = 0; i < count; ++i )
			{
				if( slists_[i].create( max ) == false )
				{
					destroy();
					return false;
				}
			}
		}

		count_ = count;
		return true;
	}

	void	lookaside::destroy()
	{
		if( slists_ != NULL )
		{
			delete [] slists_;
			slists_ = NULL;
		}

		count_ = 0;
	}

	bool	lookaside::push( size_t idx, SLIST_ENTRY* entry )
	{
		assert( entry != NULL );
		if( entry != NULL )
		{
			common::slist* stack = at( idx );
			if( stack != NULL )
			{
				if( stack->push( entry ) == false )
				{
					return false;
				}

				return true;
			}
		}

		return false;
	}

	SLIST_ENTRY*	lookaside::pop( size_t idx )
	{
		SLIST_ENTRY* entry = NULL;
		common::slist* stack = at( idx );
		if( stack != NULL )
		{
			entry = stack->pop();
		}

		return entry;
	}

	SLIST_ENTRY*	lookaside::pop_all( size_t idx )
	{
		SLIST_ENTRY* entry = NULL;
		common::slist* stack = at( idx );
		if( stack != NULL )
		{
			entry = stack->pop_all();
		}

		return entry;
	}

	size_t	lookaside::size()	const
	{
		return count_;
	}

	common::slist*	lookaside::at( size_t idx )	const
	{
		common::slist* stack = NULL;
		if( slists_ != NULL )
		{
			if( 0 <= idx && idx < count_ )
			{
				stack = &slists_[idx];
			}
		}

		return stack;
	}
}
